package{
	
	import component.Image;
	import component.Text;
	
	import flash.display.DisplayObject;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import module.Ball;
	import module.LoginPanel;
	import module.Map;
	
	import org.papervision3d.view.BasicView;
	
	import utils.Tween;
	
	public class LogoBall extends BasicView{
		
		private var ball:Ball;
		
		private var turnSpeed:int = 1; //旋转速度
		
		public function LogoBall(){
			addEventListener(Event.ADDED_TO_STAGE,init);
			this.buttonMode = true;
		}
		
		private function init(e:Event):void{
			removeEventListener(Event.ADDED_TO_STAGE,init);
			stage.color = 0;
			stage.frameRate = 40;
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			addEventListener(MouseEvent.CLICK,onClick);
			Global.stage = stage;
			preLoad();
			addChild(LoginPanel.instance);
		}
		
		/**
		 * 预加载图片
		 * */
		private function preLoad():void{
			var batchNames:Array = [];
			for(var i:int=1;i<10;i++)batchNames.push("pic"+i+".jpg");
			Image.batchLoad("resource",batchNames,function():void{
				initMain();
				addChild(Map.instance);
				Map.instance.onResize();
			});
		}
		
		
		/**加入球*/
		private function initMain():void{
			this.ball = new Ball();	
			this.scene.addChild(ball);
			startRendering();
			stage.addEventListener(Event.RESIZE,onResize);
		}
		
		/**球动起来*/
		override protected function onRenderTick(e:Event=null):void{
			if(this.ball.rotationY >= 359)this.ball.rotationY = 0;
			this.ball.rotationY += turnSpeed;
			super.onRenderTick();
			this.ball.checkIsOpenBall();
		}
		
		
		/**点击打开球*/
		private function onClick(e:MouseEvent):void{
			if(Map.instance.tweenCount==0){
				this.ball.open = true;
				turnSpeed +=1;
			}else if(Map.instance.tweenCount==8)this.ball.open = false;
			return;
			
			if(this.ball.isSurface){
				turnSpeed = 1;
				ball.surfaceEffect(false);
				LoginPanel.instance.visible = false;
			}else{
				LoginPanel.instance.visible = true;
				var oRY:int = this.ball.rotationY;
				var dRY:int = oRY>180?360:0;
				ball.surfaceEffect(true);
				Tween.to(this.ball,600,{rotationY:[oRY,dRY]},function():void{
					turnSpeed = 0;
				});
			}
		}
		
		/**窗口自适应*/
		private function onResize(e:Event):void{
			for(var i:int = 0;i<numChildren;i++){
				var child:DisplayObject = this.getChildAt(i);
				if(child.hasOwnProperty("onResize")){
					(child as Object).onResize();
				}
			}
		}
		
	}
}